//
//  UserContext.m
//  YiJuZhangShou2.0
//
//  Created by 冷悦 on 16/4/6.
//  Copyright © 2016年 Mr.X. All rights reserved.
//

#import "UserContext.h"
#import "PlistManager.h"
#import "NetworkingBaseManager.h"
#import "NetWorkingManagerFactory.h"
#import "MJExtension.h"
#import "RequestGenerator.h"
#import "UIAlertControllerUtil.h"
//#import "PersonalCenterInstance.h"

#ifndef kUserContextFileName
#define kUserContextFileName @"user"
#endif


@interface UserContext () <NetworkingBaseManagerAPISuccessCallbackDelegate,NetworkingBaseManagerValidator>

@property (nonatomic, strong)NetworkingBaseManager *loadManager;

@property (nonatomic, strong)NetworkingBaseManager *updateManager;

@end

@implementation UserContext

static UserContext *_userContext = nil;

#pragma mark - Initialize
+ (instancetype)sharedInstance{
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        _userContext = [[self alloc] init];
        
        if ([PlistManager isExistWithFileName:kUserContextFileName]) {
            NSDictionary *userDict = [_userContext loadUserFromFile];
            [_userContext mj_setKeyValues:userDict];
        }
    });
    
    return _userContext;
}

#pragma mark NetworkingBaseManagerAPISuccessCallbackDelegate
- (void)manager:(NetworkingBaseManager *)manager callAPIDidSuccessWithParams:(NSDictionary *)responseParams{
    if (manager == self.loadManager) {
        NSUInteger stateCode = [[responseParams objectForKey:@"stateCode"] unsignedIntegerValue];
        
        if(stateCode == 101){
            NSDictionary *userDict = [responseParams objectForKey:@"data"];
            [self mj_setKeyValues:userDict];
            [PlistManager saveData:userDict withFileName:kUserContextFileName];
        }
    }
    
    if (manager == self.updateManager) {
        DDLogInfo(@"%@", [responseParams description]);
        [UIAlertControllerUtil generateInfoControllerWithTitle:@"成功" message:@"更新个人资料成功"];
    }
}

#pragma mark - Delegate NetworkingBaseManagerValidator
- (BOOL)isCorrectWithCallbackData:(NSDictionary *)data{
    //    NSAssert(NO, @"未重写判断网络返回数据正确性代理事件(BaseViewModel)");
    NSInteger stateCode = [[data objectForKey:@"stateCode"] integerValue];
    if (stateCode == 100||stateCode == 101|| stateCode == 102|| stateCode == 103) {
        return YES;
    }else{
        [UIAlertControllerUtil generateInfoControllerWithTitle:[NSString stringWithFormat:@"%ld",stateCode] message:[data objectForKey:@"stateMessage"]];
        return NO;
    }
}

#pragma mark Private
- (void)saveUserToPlist:(NSDictionary *)userDict{
    [PlistManager saveData:userDict withFileName:kUserContextFileName];
}

- (NSDictionary *)loadUserFromFile{
    NSDictionary *userDict = [PlistManager loadDataWithFileName:kUserContextFileName];
    
    return userDict;
}

- (void)loadRequestWithManager:(NetworkingBaseManager *)manager andUserId:(NSUInteger)userId{
    manager.successDelegate = self;
    manager.validator = self;
    [manager loadRequest];
}

#pragma mark - Public
- (void)loadUserFromServer{
    NSUInteger userId = [AppContext sharedInstance].userId;
    
    if (userId > 0) {
        NSString *apiName = [NSString stringWithFormat:@"users/%lu", userId];
        apiName = [[RequestGenerator sharedInstance] generateCommonApiWithName:apiName];
        self.loadManager = [NetworkingManagerFactory generateSHA256Manager];
        self.loadManager.apiName = apiName;
        self.loadManager.requestType = HTTP_GET;
        [self loadRequestWithManager:self.loadManager andUserId:userId];
    }
}

- (void)updateUserInfomation{
    NSUInteger userId = [AppContext sharedInstance].userId;
    
    if (userId > 0) {
        NSDictionary *dict = [self mj_keyValuesWithIgnoredKeys:@[@"userName",@"loadManager",@"updateManager"]];
        NSString *apiName = [NSString stringWithFormat:@"users/%lu/detailInformation", userId];
        apiName = [[RequestGenerator sharedInstance] generateCommonApiWithName:apiName];
        self.updateManager = [NetworkingManagerFactory generateSHA256Manager];
        self.updateManager.apiName = apiName;
        self.updateManager.params = dict;
        self.updateManager.requestType = HTTP_PUT;
        [self loadRequestWithManager:self.updateManager andUserId:userId];
    }
}

@end
